package com.springcloud.tools.conf;

import com.springcloud.tools.common.TopicConstance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author fuc
 * @create 2020-06-09
 */
@Configuration
@Slf4j
public class RabbitMQConfig {

  @Autowired private RabbitTemplate rabbitTemplate;

  @PostConstruct
  public void simpleMessageListenerContainer() {
    rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
  }

  @Bean
  public MessageConverter messageConverter() {
    return new Jackson2JsonMessageConverter();
  }

  @Bean
  @Qualifier(TopicConstance.QUEUE_NAME_TEST)
  public Queue queue() {
    return new Queue(TopicConstance.QUEUE_NAME_TEST);
  }

  @Bean
  @Qualifier(TopicConstance.EXCHANGE_NAME_TEST)
  public TopicExchange exchange() {
    return new TopicExchange(TopicConstance.ROUTINGKEY_NAME_TEST);
  }

  @Bean
  public Binding binding(
      @Qualifier(TopicConstance.EXCHANGE_NAME_TEST) TopicExchange exchange,
      @Qualifier(TopicConstance.QUEUE_NAME_TEST) Queue queue) {
    return BindingBuilder.bind(queue).to(exchange).with(TopicConstance.ROUTINGKEY_NAME_TEST);
  }
}
